 <cfquery 
       name="conds" datasource="exp" >

       SELECT distinct conditions.description, trial.condid
       FROM trial, experiment, conditions, stimuli
       where  trial.condid=conditions.id
       and trial.stimid=stimuli.id
       and trial.expid = experiment.id
       and experiment.id = #expid#
       
</cfquery> 
<cfscript> 
//Use an absolute path for the files. ---> 
theDir=GetDirectoryFromPath(GetCurrentTemplatePath()); 
theFile=theDir & "experiment.csv"; 
</cfscript>

    <!--- Create the file with column header's. It is crucial that you have all the outputed text on one line with no spaces between the comma and the next column header.--->
    <cffile action="write"
             file=#theFile#
             output="participantid,conddescription,location,answer,anscorrect,h1,m1,s1,h2,m2,s2,time in seconds"
             addnewline="yes">

    <!--- Output the contents of the export_contacts query --->
    <cfoutput>
        <cfloop query="conds">
	<cfquery 
       name="getparts" datasource="exp" >
    	select participantid, conditions.description as conddescript, stimuli.location as location, givesanswer.answer as answer, stimuli.answer as correctanswer, hour, minute, second, hour2, minute2, second2
    	from givesanswer, trial, stimuli, conditions
    	where conditions.id=#condid# 
    	and trial.stimid = stimuli.id
    	and conditions.id = trial.condid
    	and givesanswer.trialid = trial.id
    	order by participantid     
</cfquery> 




    <cfloop query="getparts">
        <!--- Append (Insert) the contents of the query into the already created CSV file. Make sure that you keep all the output on one line exactly like the column header--->
	<cfset MyTime="#hour#:#minute#:#second#">  
	<cfset MyAnotherTime="#hour2#:#minute2#:#second2#">    
	<cfset MyDateTime=CreateDateTime(Year(Now()),Month(Now()),Day(Now()),#hour#,#minute#,#second#)>  
	<cfset MyDateTime2=CreateDateTime(Year(Now()),Month(Now()),Day(Now()),#hour2#,#minute2#,#second2#)>  
	<cfset time = DateDiff("s", "#MyDateTime#", "#MyDateTime2#")>
        <cffile action="append"
                 file="#theFile#"
                  output="#getparts.participantid#, #getparts.conddescript#,#getparts.location#, #getparts.answer#, #getparts.correctanswer#, #getparts.hour#, #getparts.minute#, #getparts.second#, #getparts.hour2#, #getparts.minute2#, #getparts.second2#, #time#,"
                 addnewline="yes">
</cfloop>
        </cfloop>
    </cfoutput>
<cfquery name="getemail" datasource="exp" >
select * from user where id=#session.id#
</cfquery>


<cfmail type="html" 
from="#getemail.email#" 
subject="Experiment CSV" 
to="#getemail.email#"
server="mr1.dcs.gla.ac.uk"
spoolenable="no">

<cfmailparam file="#theFile#">

Attached find the CSV file
</cfmail> 

<cfset session.message = "Your CSV file has been emailed to you">
<cflocation url="/ecada/analyse/seeexp.cfm?id=#expid#">

